package com.swf.seed.os.command.impl;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.ParseException;

import com.swf.seed.base.SdLetter;
import com.swf.seed.os.annotation.Command;

@Command("ip")
public class IpCommand extends CommandAdaptor {

	@Override
	public void option() {
		options.addOption(SdLetter.h, "help", false, "show ip usage");
		options.addOption(SdLetter.s, "show", false, "show ip address");

	}

	@Override
	void customizedExecute(CommandLine commandLine) throws ParseException {
		if (commandLine.hasOption(SdLetter.s)) {
			try {
				Enumeration allNetInterfaces = NetworkInterface
						.getNetworkInterfaces();
				InetAddress ip = null;
				Set<String> ipSet = new HashSet<String>();
				while (allNetInterfaces.hasMoreElements()) {
					NetworkInterface netInterface = (NetworkInterface) allNetInterfaces
							.nextElement();
					Enumeration addresses = netInterface.getInetAddresses();
					System.out.println(netInterface);
					while (addresses.hasMoreElements()) {
						ip = (InetAddress) addresses.nextElement();
						System.out.println(ip.getLocalHost());
						if (ip != null && ip instanceof Inet4Address) {
							ipSet.add(ip.getLocalHost().toString());
						}
					}
				}
				for (String ips:ipSet){
					System.out.println(ips);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}
